<?php

namespace App\Http\Controllers\Api\Website;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\SendMessageRequest;
use App\model\VerifyCode;


class SendMessageController extends Controller
{
    public function send(SendMessageRequest $request)
    {
        $mobile=$request->mobile;
        $sms = app('sms');
        $code=rand(1000,9999);
        $verifyCode= VerifyCode::where('account',$mobile)->first();
        if ($verifyCode){
            $time=$verifyCode->updated_at ?? $verifyCode->created_at;
            if (strtotime(now())-strtotime($time)<60){
                throw new ApiException('短信发送太频繁');
            }
        }else{
            $verifyCode=new VerifyCode();
            $verifyCode->account=$mobile;
        }
        try {
            $sms->send($mobile, [
               # 'template' => 'SMS_113155005',
                'template' => 'SMS_150181420',
                'data' => [
                    'code' => $code
                ],
            ]);
        } catch (\Exception $exception) {
            \Log::info($exception->getExceptions());
            throw  new ApiException('短信发送失败');

        }
        $verifyCode->verify_code_num=$code;
        $verifyCode->save();
        return response()->json([
            'code'=>0,
            'data'=>'短信发送成功',
        ]);
    }
}
